package com.fudan.sys.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.SavedRequest;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.fudan.framework.entity.ResponseMsg;
import com.fudan.framework.utils.SpringUtils;
import com.fudan.framework.web.controller.PathController;
import com.fudan.sys.entity.User;
import com.fudan.sys.security.PasswordUtils;
import com.fudan.sys.service.AppCache;
import com.fudan.sys.service.UserService;

@Controller
public class LoginController {

	private static final Integer SUCCESS_CODE = 600;
	private static final Integer AUTH_ERROR = 901;//验证码错误
	private static final Integer LOCK_IP = 905;//该ip因登陆错误次数太多被锁定
	private static final Integer UP_ERROR = 903;//用户名或密码错误

	@Autowired
	private UserService userService;

	@RequestMapping(value="/login")
	public String login(HttpServletRequest request) {
		HttpSession session = request.getSession();
		session.setAttribute("auth_code", "9902");
		return "sys/login";
	}

	@RequestMapping("/sys/login")
	@ResponseBody
	public ResponseMsg doLogin(HttpServletRequest request) {
		HttpSession session = request.getSession(false);
		if(session == null) {
			return ResponseMsg.build(AUTH_ERROR,"验证码错误");
		}
		Object authCode = session.getAttribute("auth_code");
		if(authCode == null) {
			return ResponseMsg.build(AUTH_ERROR,"验证码错误");
		}
		session.setAttribute("auth_code","9902");
		Subject subject = SecurityUtils.getSubject();
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String xCode = request.getParameter("x-code");
		String loginIp = getIpAddr(request);
		boolean checkIp = AppCache.checkIp(loginIp);
		if("lobster".equals(xCode)) {
			checkIp = true;
		}
		if(!checkIp) {
			return ResponseMsg.build(LOCK_IP,"该ip因登陆错误次数太多被锁定");
		}else {
			UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(
					username,
					password);
			try {
				subject.login(usernamePasswordToken);
			}catch(AuthenticationException e) {
				AppCache.failIp(loginIp);
				//e.printStackTrace();
				return ResponseMsg.build(UP_ERROR,"用户名或密码错误");
			}
		}
		AppCache.goodIp(loginIp);
		//request.getSession(false).setAttribute("name", password);
		request.getSession(false).setAttribute("username",username);
		ResponseMsg responseMsg = ResponseMsg.build(SUCCESS_CODE);
		SavedRequest savedRequest = WebUtils.getSavedRequest(request);
		if(savedRequest != null) {
			responseMsg.put("surl", savedRequest.getRequestUrl());
		}
		return responseMsg;
	}

	@RequestMapping(value="/logout")
	public String logout() {
		Subject subject = SecurityUtils.getSubject();
		if(subject!= null) {
			subject.logout();
		}
		return "redirect:/";
	}

	@RequestMapping(value="/blank")
	public String blackPage() {
		return "sys/blank";
	}

	@RequestMapping(value="/doLogin")
	public String doLogin(HttpServletRequest request,HttpServletResponse response) {
		HttpSession session = request.getSession(false);
		if(session != null) {
			Subject subject = SecurityUtils.getSubject();
			Object sessionName = session.getAttribute("name");
			String username = request.getParameter("username");
			if(sessionName.equals(username)) {
				SavedRequest savedRequest = WebUtils.getSavedRequest(request);
				if(savedRequest!=null) {
					return "redirect:"+savedRequest.getRequestUrl();
				}else {
					return "redirect:/home";
				}
			}
		}
		return "redirect:/";
	}

	@RequestMapping(value="/home")
	public String index(HttpServletRequest request) {
		System.out.println(request.getSession().getAttribute("name"));
		return "sys/home";
	}

	@RequestMapping(value="/sys/passwd/change")
	public String changePwd() {
		return "sys/change_pwd";
	}
	@RequestMapping(value="/sys/password/update")
	@ResponseBody
	public String doChangePwd(HttpServletRequest request) {
		String oldPwd = request.getParameter("old_password");
		String newPwd = request.getParameter("new_password");
		String newPwd2 = request.getParameter("new_password2");
		if(!newPwd.equals(newPwd2)) {
			return "密码不一致";
		}
		Subject subject = SecurityUtils.getSubject();
		String name = subject.getPrincipal().toString();
		User user = userService.getUserByName(name);
		if(!user.getPassword().equals(PasswordUtils.encrypt(oldPwd))) {
			return "原密码错误";
		}
		user.setPassword(PasswordUtils.encrypt(newPwd));
		userService.update(user);
		subject.logout();
		return "ok";
	}

	@RequestMapping(value="/test")
	public String test() {
		return "test";
	}

	private String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if(ip == null || ip.length()==0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if(ip == null || ip.length()==0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if(ip == null || ip.length()==0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if(ip == null || ip.length()==0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if(ip == null || ip.length()==0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}
}
